package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.DeviceTypeMapper;
import com.xidian.zhiancloud.dao.EqFacMngMapper;
import com.xidian.zhiancloud.dao.OhRegisterMapper;
import com.xidian.zhiancloud.dao.OhTypeMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.equipFacility.OhLedgerQO;
import com.xidian.zhiancloud.qo.equipFacility.OhRegisterQO;
import com.xidian.zhiancloud.vo.equipFacility.OhLedgerVO;
import com.xidian.zhiancloud.vo.equipFacility.OhRegisterVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 检修登记
 * @Author: 任启亮
 * @Date: 2020/11/11
 */
@Service
public class OhRegisterService extends ServiceImpl<OhRegisterMapper, OhRegister> implements IService<OhRegister> {
    public int count = 0;
    public Date date = new Date();

    @Autowired
    private OhRegisterMapper ohRegisterMapper;

    @Autowired
    private EqFacMngMapper eqFacMngMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;

    @Autowired
    private OhTypeMapper ohTypeMapper;

    /**
     * 添加检修登记记录
     * @param ohRegister
     * @return
     */
    public Boolean add(OhRegister ohRegister){

        Date temp = new Date();
        if (count == 0) {
            date = temp;
        }
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(temp);
        cal2.setTime(date);
        if (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
                cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)) {
            count++;
        } else {
            count = 0;
        }
        String str = "B"+cal1.get(Calendar.YEAR) + String.format("%02d", cal1.get(Calendar.MONTH) + 1) +
                String.format("%02d", cal1.get(Calendar.DAY_OF_MONTH)) + String.format("%05d", count);
        ohRegister.setRegisterNo(str);

        int insert = ohRegisterMapper.insert(ohRegister);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        return true;
    }

    /**
     * 根据id获取检修登记信息
     * @param id
     * @return
     */
    public OhRegisterVO getById(Long id){

        OhRegister ohRegister = ohRegisterMapper.selectById(id);

        OhRegisterVO vo = new OhRegisterVO();
        BeanUtils.copyProperties(ohRegister,vo);

        EqFacMng eqFacMng = eqFacMngMapper.selectById(vo.getEqFacId());
        vo.setDeviceName(eqFacMng.getName());
        vo.setDeviceStatus(eqFacMng.getEquipStatus());

        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceType(deviceType == null ? "该类型不存在" : deviceType.getName());
        Organization organization = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

        OhType ohType = ohTypeMapper.selectById(vo.getOhTypeId());
        vo.setOhTypeName(ohType == null ? "该检修类型不存在" : ohType.getName());

        String names = "";
        String repairUsersId = vo.getRepairUsersId();
        long[] array = Arrays.stream(repairUsersId.split(",")).mapToLong(Long::parseLong).toArray();
        for (long i : array) {
            SysUser sysUser = sysUserMapper.selectById(i);
            if(sysUser != null){
                names += sysUser.getName() + ",";
            }
        }
        vo.setRepairUsersName(names);

        return vo;
    }

    /**
     * 列表查询
     * @param ohRegisterQO
     * @return
     */
    public IPage<OhRegisterVO> getListByQO(OhRegisterQO ohRegisterQO) {
        Page<OhRegisterVO> page = new Page<>(ohRegisterQO.getCurrent(), ohRegisterQO.getSize());

        IPage<OhRegisterVO> list = ohRegisterMapper.selectByQO(page, ohRegisterQO);

        list.getRecords().forEach(obj -> {

            Organization organization = organizationMapper.selectById(obj.getDepartmentId());
            obj.setDepartmentName(organization==null ? "该部门不存在" : organization.getName());
            DeviceType deviceType = deviceTypeMapper.selectById(obj.getDeviceTypeId());
            obj.setDeviceType(deviceType==null ? "该类型不存在" : deviceType.getName());
            OhType ohType = ohTypeMapper.selectById(obj.getOhTypeId());
            obj.setOhTypeName(ohType == null ? "该检修类型不存在" : ohType.getName());

            String names = "";
            long[] array = Arrays.stream(obj.getRepairUsersId().split(",")).mapToLong(Long::parseLong).toArray();
            for (long i : array) {
                SysUser sysUser = sysUserMapper.selectById(i);

                if(sysUser != null){
                    names += sysUser.getName() + ",";
                }
            }
            obj.setRepairUsersName(names);
        });

        return list;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean submitById(Long id) {

        OhRegister ohRegister = ohRegisterMapper.selectById(id);
        if(ohRegister == null){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }
        ohRegister.setIsSubmitted(1);
        int ret = ohRegisterMapper.updateById(ohRegister);

        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }

        return true;
        /*OhRegister ohRegister = new OhRegister();
        ohRegister.setId(id);
        ohRegister.setIsSubmitted(submit);
        if (submit == 0) {
            return false;
        }
        return updateById(ohRegister);*/
    }

    /**
     * 检修台账  根据id查询
     * @param id
     * @return
     */
    public OhLedgerVO getLedgerById(Long id){

        OhRegister ohRegister = ohRegisterMapper.selectById(id);
        OhLedgerVO vo = new OhLedgerVO();
        BeanUtils.copyProperties(ohRegister,vo);

        EqFacMng eqFacMng = eqFacMngMapper.selectById(vo.getEqFacId());
        if(eqFacMng != null){
            vo.setDeviceName(eqFacMng.getName()); //设备名称
            vo.setModel(eqFacMng.getModel());//设备规格型号
            vo.setDeviceStatus(eqFacMng.getEquipStatus());//设备状态

            //管辖部门名称
            Organization organization = organizationMapper.selectById(vo.getDepartmentId());
            vo.setDepartmentName(organization == null ? "该管辖部门不存在" : organization.getName());

            vo.setPosition(eqFacMng.getPosition());//区域位置

            //设备类型名称
            DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
            vo.setDeviceTypeName(deviceType == null ? "该设备类型不存在": deviceType.getName());
        }

        String names = "";
        long[] array = Arrays.stream(vo.getRepairUsersId().split(",")).mapToLong(Long::parseLong).toArray();
        for (long i : array) {
            SysUser sysUser = sysUserMapper.selectById(i);
            if(sysUser != null){
                names += sysUser.getName() + ",";
            }
        }
        vo.setRepairUsersName(names);

        OhType ohType = ohTypeMapper.selectById(vo.getOhTypeId());
        vo.setOhTypeName(ohType == null ? "该检修类型不存在" : ohType.getName());

        return vo;
    }


    /**
     * 检修台账  列表查询
     * @param ohLedgerQO
     * @return
     */
    public IPage<OhLedgerVO> getLedgerListByQO(OhLedgerQO ohLedgerQO) {
        Page<OhLedgerVO> page =new Page<>(ohLedgerQO.getCurrent(),ohLedgerQO.getSize());

        IPage<OhLedgerVO> list = ohRegisterMapper.selectByLedgerQO(page, ohLedgerQO);

        list.getRecords().forEach(obj -> {

            Organization org = organizationMapper.selectById(obj.getDepartmentId());
            obj.setDepartmentName(org == null ? "该部门不存在" : org.getName());
            DeviceType deviceType = deviceTypeMapper.selectById(obj.getDeviceTypeId());
            obj.setDeviceTypeName(deviceType == null ? "该设备类型不存在" : deviceType.getName());

            String names = "";
            long[] array = Arrays.stream(obj.getRepairUsersId().split(",")).mapToLong(Long::parseLong).toArray();
            for (long i : array) {
                SysUser sysUser = sysUserMapper.selectById(i);
                if(sysUser != null){
                    names += sysUser.getName() + ",";
                }
            }
            obj.setRepairUsersName(names);
        });

        return list;
    }
}
